/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * BehaviorConfigPanel.java
 *
 * Created on 07/02/2010, 12:06:43
 */
package org.p2psimulator.gui.panel;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.Vector;
import javax.swing.JFileChooser;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.JTableHeader;
import org.p2psimulator.config.BehaviorConfig;
import org.p2psimulator.entity.behavior.BehaviorTypes;
import org.p2psimulator.util.dialogs.AlertBox;

/**
 *
 * @author Amorim
 */
public class BehaviorConfigPanel extends ConfigPanel {

    /** Creates new form BehaviorConfigPanel */
    public BehaviorConfigPanel() {
        initComponents();
    }

    public void setSelectedRow(int row) {
        table.setRowSelectionAllowed(true);
        table.setRowSelectionInterval(row, row);
    }

    public BehaviorConfig getSelectedBehaviorConfig(int maxPeers) {

        BehaviorTypes[] types = {BehaviorTypes.HONEST, BehaviorTypes.SELFISH,
            BehaviorTypes.MALICIOUS, BehaviorTypes.DISTURBING, BehaviorTypes.EVIL};
        JTableHeader header = table.getTableHeader();

        int i = table.getSelectedRow() > 0 ? table.getSelectedRow() : 0;
        Map<BehaviorTypes, Integer> map = new HashMap<BehaviorTypes, Integer>();


        int k = 1;

        while (k < table.getColumnCount()) {

            String str = (String) header.getColumnModel().getColumn(k).getHeaderValue();
            BehaviorTypes t = null;

            if (str.equals("Honest")) {
                t = BehaviorTypes.HONEST;
            } else if (str.equals("Malicious")) {
                t = BehaviorTypes.MALICIOUS;
            } else if (str.equalsIgnoreCase("Selfish")) {
                t = BehaviorTypes.SELFISH;
            } else if (str.equalsIgnoreCase("Disturbing")) {
                t = BehaviorTypes.DISTURBING;
            } else if (str.equalsIgnoreCase("Evil")) {
                t = BehaviorTypes.EVIL;
            }
            if (table.getValueAt(i, k) == null) {
                continue;
            }
            try {
                Double d = new Double((Double) table.getValueAt(i, k));
                Double tax = d / 100;
                Double perc = maxPeers * tax;
                map.put(t, perc.intValue());

                //System.out.println("## " + t.getTypeName() + " criados: " + perc.intValue());
            } catch (Exception e) {
                continue;
            } finally {
                k++;
            }

        }
        BehaviorConfig bcfg = new BehaviorConfig(map);
        BehaviorConfig.disturbingInteractions = mainFrame.getEnvironmentConfigPanel().getDisturbingInteractions();
        BehaviorConfig.leavingrate = mainFrame.getEnvironmentConfigPanel().getLeaveCondition();
        BehaviorConfig.disturbingrate = mainFrame.getEnvironmentConfigPanel().getDisturbingRate();
        bcfg.setCfgId((table.getValueAt(i, 0).toString()));

        return bcfg;
    }

    public Vector<BehaviorConfig> getAllBehaviorConfigs(int maxPeers) {

        Vector<BehaviorConfig> cfgs = new Vector<BehaviorConfig>();
        BehaviorTypes[] types = {BehaviorTypes.HONEST, BehaviorTypes.SELFISH,
            BehaviorTypes.MALICIOUS, BehaviorTypes.DISTURBING, BehaviorTypes.EVIL};
        JTableHeader header = table.getTableHeader();
        for (int i = 0; i < table.getRowCount(); i++) {
            Map<BehaviorTypes, Integer> map = new HashMap<BehaviorTypes, Integer>();


            int k = 1;

            while (k < table.getColumnCount()) {

                String str = (String) header.getColumnModel().getColumn(k).getHeaderValue();
                BehaviorTypes t = null;

                if (str.equals("Honest")) {
                    t = BehaviorTypes.HONEST;
                } else if (str.equals("Malicious")) {
                    t = BehaviorTypes.MALICIOUS;
                } else if (str.equalsIgnoreCase("Selfish")) {
                    t = BehaviorTypes.SELFISH;
                } else if (str.equalsIgnoreCase("Disturbing")) {
                    t = BehaviorTypes.DISTURBING;
                } else if (str.equalsIgnoreCase("Evil")) {
                    t = BehaviorTypes.EVIL;
                }
                if (table.getValueAt(i, k) == null) {
                    continue;
                }
                try {
                    Double d = new Double((Double) table.getValueAt(i, k));
                    Double tax = d / 100;
                    Double perc = maxPeers * tax;
                    map.put(t, perc.intValue());

                    //System.out.println("## " + t.getTypeName() + " criados: " + perc.intValue());
                } catch (Exception e) {
                    continue;
                } finally {
                    k++;
                }

            }
            BehaviorConfig bcfg = new BehaviorConfig(map);
            BehaviorConfig.disturbingInteractions = mainFrame.getEnvironmentConfigPanel().getDisturbingInteractions();
            BehaviorConfig.leavingrate = mainFrame.getEnvironmentConfigPanel().getLeaveCondition();
            BehaviorConfig.disturbingrate = mainFrame.getEnvironmentConfigPanel().getDisturbingRate();
            bcfg.setCfgId((table.getValueAt(i, 0).toString()));
            cfgs.add(bcfg);
        }

        return cfgs;
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        table = new javax.swing.JTable();
        toolBar = new javax.swing.JToolBar();
        addRowButton = new javax.swing.JButton();
        removeRowButton = new javax.swing.JButton();

        table.setFont(new java.awt.Font("Tahoma", 0, 10)); // NOI18N
        table.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {"1",  new Double(100.0),  new Double(0.0),  new Double(0.0),  new Double(0.0),  new Double(0.0)}
            },
            new String [] {
                "Id", "Honest", "Selfish", "Malicious", "Disturbing", "Evil"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.Double.class, java.lang.Double.class, java.lang.Double.class, java.lang.Double.class, java.lang.Double.class
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }
        });
        jScrollPane1.setViewportView(table);
        table.getColumnModel().getColumn(0).setPreferredWidth(10);
        table.getColumnModel().getColumn(1).setPreferredWidth(10);
        table.getColumnModel().getColumn(2).setPreferredWidth(10);
        table.getColumnModel().getColumn(3).setPreferredWidth(10);
        table.getColumnModel().getColumn(4).setPreferredWidth(10);
        table.getColumnModel().getColumn(5).setPreferredWidth(10);

        toolBar.setRollover(true);

        addRowButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/add.png"))); // NOI18N
        addRowButton.setBorderPainted(false);
        addRowButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addRowButtonActionPerformed(evt);
            }
        });
        toolBar.add(addRowButton);

        removeRowButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/remove.png"))); // NOI18N
        removeRowButton.setBorderPainted(false);
        removeRowButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                removeRowButtonActionPerformed(evt);
            }
        });
        toolBar.add(removeRowButton);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 387, Short.MAX_VALUE)
            .addComponent(toolBar, javax.swing.GroupLayout.DEFAULT_SIZE, 387, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 140, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(toolBar, javax.swing.GroupLayout.PREFERRED_SIZE, 19, javax.swing.GroupLayout.PREFERRED_SIZE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void addRowButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addRowButtonActionPerformed
        // TODO add your handling code here:
        DefaultTableModel model = (DefaultTableModel) table.getModel();
        model.addRow(new Object[model.getColumnCount()]);
    }//GEN-LAST:event_addRowButtonActionPerformed

    private void removeRowButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_removeRowButtonActionPerformed
        // TODO add your handling code here:
        DefaultTableModel model = (DefaultTableModel) table.getModel();

        int idx = table.getSelectedRow();

        if (idx < 0) {
            return;
        }
        model.removeRow(idx);
        if (idx > 0) {
            setSelectedRow(idx - 1);
        }
    }//GEN-LAST:event_removeRowButtonActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton addRowButton;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JButton removeRowButton;
    private javax.swing.JTable table;
    private javax.swing.JToolBar toolBar;
    // End of variables declaration//GEN-END:variables

    public void saveToFile(){
         PrintWriter writer = null;
        try {
            JFileChooser fileChooser = new JFileChooser();
            File chosenFile = null;
            int retValue = fileChooser.showOpenDialog(null);
            if (retValue == JFileChooser.APPROVE_OPTION) {
                chosenFile = fileChooser.getSelectedFile();
            }
            if (chosenFile == null) {
                return;
            }
            writer = new PrintWriter(chosenFile);

            JTableHeader header = table.getTableHeader();
            String line = "";
            for (int k = 0; k < table.getColumnCount(); k++) {
                String str = (String) header.getColumnModel().getColumn(k).getHeaderValue();

                line += str;

                if ((k + 1) < table.getColumnCount()) {
                    line += ";";
                }
            }
            writer.println(line);
            for (int i = 0; i < table.getRowCount(); i++) {
                line = "";
                for (int j = 0; j < table.getColumnCount(); j++) {
                    String str = "" + table.getValueAt(i, j);
                    if (str == null) {
                        str = "0";
                    }
                    line += str;
                    if ((j + 1) < table.getColumnCount()) {
                        line += ";";
                    }
                }
                writer.println(line);
            }

        } catch (FileNotFoundException ex) {
            new AlertBox(null, true, "Save File Fail");
        } finally {
            writer.close();
        }
    }
    
    public void loadFromFile(){
        BufferedReader reader = null;
        try {
            // TODO add your handling code here:
            JFileChooser fileChooser = new JFileChooser();
            File chosenFile = null;
            int retValue = fileChooser.showOpenDialog(null);
            if (retValue == JFileChooser.APPROVE_OPTION) {
                chosenFile = fileChooser.getSelectedFile();
            }
            if (chosenFile == null) {
                return;
            }
            reader = new BufferedReader(new FileReader(chosenFile));
            String line = reader.readLine();

            // skip titles
            line = reader.readLine();

            int row = 0;
            while (line != null) {

                if (table.getRowCount() <= row) {
                    DefaultTableModel model = (DefaultTableModel) table.getModel();
                    model.addRow(new Object[model.getColumnCount()]);
                }

                StringTokenizer strTok = new StringTokenizer(line, ";");

                int col = 0;
                while (strTok.hasMoreTokens()) {
                    table.setValueAt(Double.parseDouble(strTok.nextToken()), row, col);
                    col++;
                }
                row++;
                line = reader.readLine();
            }
            reader.close();
        } catch (IOException ex) {
            new AlertBox(null, true, "Load File Fail");
        } catch (Exception ex) {
            new AlertBox(null, true, "Bad File Format - Check for non numeric characters on cell's velues");
        }
    }
    
    public JTable getTable() {
        return table;
    }
    
}
